package org.zhangkun.jmsg.webserver.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.zhangkun.jmsg.webserver.inter.Servlet;
import org.zhangkun.jmsg.webserver.server.Request;
import org.zhangkun.jmsg.webserver.server.Response;
import org.zhangkun.jmsg.webserver.server.WEBServer;
import org.zhangkun.jmsg.webserver.util.MD5;

public class ReadFile implements Servlet {

	private static Map<String, String> files = new HashMap<String, String>();
	private static byte[] buffer = new byte[1024];

	@Override
	public void doRequest(Request rt, Response rs) throws Exception {
		// TODO Auto-generated method stub
		String fid = rt.getParameter("fid");
		if (fid != null) {
			String filePath = files.get(fid);
			File file = new File(filePath);
			String memi = WEBServer.instance.getStaticRes().getMIME(filePath);
			System.out.println("filePATH=" + filePath + " MEMI=" + memi);

			if (memi != null) {
				rs.setContentType(memi);
				rs.setContentLength(file.length());
				rs.setBuffer(false);
				if (file.exists()) {
					FileInputStream fis = null;
					try {
						fis = new FileInputStream(file);
						int length = 0;
						while ((length = fis.read(buffer)) != -1)
							rs.write(buffer, 0, length);
					} finally {
						if (fis != null)
							fis.close();
					}
				}
			}
		}
	}

	private static int id;

	public static String getFilePath(String fid) {
		return files.get(fid);
	}

	public synchronized static String getFileID(String file) {
		String key = null;
		if (ReadFile.files.containsValue(file)) {
			Iterator<String> keys = files.keySet().iterator();
			while (keys.hasNext()) {
				String k = keys.next();
				if (files.get(k).equals(file))
					return k;
			}
		} else {
			id++;
			key = MD5
					.getMD5((System.currentTimeMillis() + "-" + id).getBytes());
			files.put(key, file);
		}
		return key;
	}

}
